<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\imgick;

use app\service\BaseService;

class ImagickService extends BaseService
{
    public static function pdf2png($pdf, $path, string $filesName = '')
    {
        try {
            $im = new \Imagick();
            $im->setCompressionQuality(100);
            $im->setResolution(300, 300);
            $im->readImage($pdf);
            $canvas = new \Imagick();
            $imgNum = $im->getNumberImages();
            foreach ($im as $k => $sub) {
                $sub->setImageFormat('jpeg');
                $sub->stripImage();
                $sub->trimImage(0);
                $width = $sub->getImageWidth() + 10;
                $height = $sub->getImageHeight() + 10;
                if ($k + 1 == $imgNum) {
                    $height += 10;
                }
                $canvas->newImage($width, $height, new \ImagickPixel('white'));
                $canvas->compositeImage($sub, \Imagick::COMPOSITE_DEFAULT, 5, 5);
            }
            $canvas->resetIterator();
            $filename = $path . '/' . $filesName . '.jpg';
            if ($canvas->appendImages(true)->writeImage($filename)) {
                $return = $filename;
            }
            $im->clear();
            $im->destroy();
            return $return;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}
